package com.pvdnc.systemdebugger.compacter.utils;

import android.os.StrictMode;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class IOUtils {
    public static byte[] readInputStream(InputStream inputStream,boolean closeStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        if(closeStream) inputStream.close();//关闭IS流
        return bos.toByteArray();
    }

    public static class File{
        public static byte[] readData(String filePath)throws Exception{
            FileInputStream fis=new FileInputStream(filePath);
            return readInputStream(fis,true);
        }

        public static void saveData(String filePath,byte[] data,boolean append)throws Exception {
            java.io.File file = new java.io.File(filePath);
            if (file.exists()) file.createNewFile();
            FileOutputStream fos = new FileOutputStream(filePath, append);
            fos.write(data);
            fos.close();
        }

        public static void copy(String srcPath,String dstPath) throws Exception {
            byte[] data= readData(srcPath);
            saveData(dstPath,data,false);
        }
    }

    public static class Network{
        static{
            //避免NetworkOnMainThread错误
            StrictMode.ThreadPolicy threadPermitAll=new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(threadPermitAll);
        }

        public static byte[] downloadData(final String urlStr) throws Exception {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            byte[] data = readInputStream(is, true);
            if(data==null||data.length==0)throw new Exception("fail to download "+urlStr);
            return data;
        }
    }
}
